package cn.qiyu5522.tk_ems.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.qiyu5522.tk_ems.entity.Company;
import cn.qiyu5522.tk_ems.entity.dto.CompanyDTO;
import cn.qiyu5522.tk_ems.entity.dto.QueryParamDTO;
import cn.qiyu5522.tk_ems.mapper.CompanyMapper;
import cn.qiyu5522.tk_ems.result.CustomMapResult;
import cn.qiyu5522.tk_ems.result.R;
import cn.qiyu5522.tk_ems.retrofit.IdGeneratorApi;
import cn.qiyu5522.tk_ems.service.CompanyService;
import cn.qiyu5522.tk_ems.utils.RedisKey;
import cn.qiyu5522.tk_ems.utils.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Tonkey
 * @since 2023-02-19
 */
@Slf4j
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService {

    @Resource
    private IdGeneratorApi idGeneratorApi;
    @Resource
    private RedisUtil redisUtil;
    @Override
    public R queryCompanyByPageCondition(QueryParamDTO<CompanyDTO> queryParamDTO) {
        CompanyDTO condition = queryParamDTO.getCondition();
        IPage<Company> companyIPage = new Page<>(queryParamDTO.getCurrentPage(), queryParamDTO.getPageSize());
        LambdaQueryWrapper<Company> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 公司名称模糊匹配
        lambdaQueryWrapper.like(ObjectUtil.isNotEmpty(condition.getName()), Company::getName, condition.getName())
        // 公司代码精确匹配
        .eq(ObjectUtil.isNotEmpty(condition.getCode()),Company::getCode,condition.getCode());
        baseMapper.selectPage(companyIPage, lambdaQueryWrapper);
        // 封装返回结果
        Map<String, Object> map = CustomMapResult.packagingResult(companyIPage.getRecords(), queryParamDTO.getCurrentPage(), queryParamDTO.getPageSize(), companyIPage.getTotal());
        return R.ok().data("companyIPage", map);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R saveMore(List<CompanyDTO> companyDTOS) {
        // 待添加的学生信息集合
        List<Company> companies = new ArrayList<>(companyDTOS.size());
        Company company = null;
        // 年份
        String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        year= year.substring(year.length() - 2);
        for (CompanyDTO companyDTO  : companyDTOS) {
            // 对象转换将VO类型转为实体类型
            company = new Company();
            BeanUtils.copyProperties(companyDTO, company);
            String customId = idGeneratorApi.getDefaultId(year);
            company.setId(Long.valueOf(customId));
            // mp自动填充
            /****/
            companies.add(company);
        }
        // 添加
        Integer integer = baseMapper.insertBatchSomeColumn(companies);
        // 添加成功，刷新Redis中的缓存
        if(integer>0){
            // 查询所有公司的编号与名称、编码 存入redis
            QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id", "name","code");
            List<Company> departmentList = baseMapper.selectList(queryWrapper);
            redisUtil.set(RedisKey.COMPANY_ID_AND_NAME_AND_CODE,departmentList,RedisKey.EXPIRE_ONE_DAY);
        }
        return integer > 0 ? R.ok().message("企业添加成功") : R.error().message("企业添加失败");
    }

    @Override
    public R removeMore(List<Long> ids) {
        int i = baseMapper.deleteBatchIds(ids);
        if(i>0){
            // 更新Redis 里的值
            QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id", "name","code");
            List<Company> departmentList = baseMapper.selectList(queryWrapper);
            redisUtil.set(RedisKey.COMPANY_ID_AND_NAME_AND_CODE, departmentList, RedisKey.EXPIRE_ONE_DAY);
        }
        return i > 0 ? R.ok().message("企业删除成功") : R.error().message("企业删除失败");
    }

    @Override
    public List<Company> queryForIdAndNameAndCode() {
        List<Company> companies = new ArrayList<>();
        log.info("从Redis中拿取 企业编号与名称、编码列表");
        companies = (List<Company>) redisUtil.get(RedisKey.COMPANY_ID_AND_NAME_AND_CODE);
        if (CollectionUtil.isEmpty(companies)) {
            log.info("Redis中无 企业编号与名称、编码列表 ");
            // 将院系的编号与名称存入
            QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id", "name","code");
            companies = baseMapper.selectList(queryWrapper);
            if (companies.size() != 0) {
                log.info("将 企业编号与名称、编码列表 存入redis");
                redisUtil.set(RedisKey.COMPANY_ID_AND_NAME_AND_CODE, companies, RedisKey.EXPIRE_ONE_DAY);
            }
        }
        return companies;
    }

    @Override
    public R queryByCode(Long code) {
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjectUtil.isNotEmpty(code),"code",code);
        List<Company> companies = baseMapper.selectList(queryWrapper);
        return companies.size() == 0?
                R.ok().message("公司编码可用").data("flag",true):
                R.ok().message("公司编码不可用").data("flag",false);
    }

    @Override
    public R queryForNameAndIdAndCode() {
        // 获取登录用户角色
        List<String> roleList = StpUtil.getRoleList();
//        boolean anyMatch = roleList.stream().anyMatch(s -> "company".equals(s));
//        // 企业登录
//        if(anyMatch){
//            // 拿到企业登录id，该id 就是 企业id
//            Long companyId =Long.valueOf(((String)StpUtil.getLoginId()).split("-")[0]) ;
//            // 返回该企业的名称和编号、编码
//            Company company = baseMapper.selectById(companyId);
//            return R.ok().data("companyIdAndNameAndCodeList",new ArrayList<Company>().add(company));
//        }
        LambdaQueryWrapper<Company> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Company::getId,Company::getName,Company::getCode);
        List<Company> companies = baseMapper.selectList(lambdaQueryWrapper);
        return R.ok().data("companyIdAndNameAndCodeList",companies);
    }

    @Override
    public R queryCompanyInfoById(Long id) {
        Company company = baseMapper.selectById(id);
        return R.ok().data("companyInfo",company);
    }
}
